# -*- coding:utf-8 -*-
import os,sys
import gzip
import StringIO
import re
import traceback
import time
from httplib import HTTPSConnection
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, os.pardir))
import supeanut_config
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
from mylog import mylog


'''
作者：supeanut
创建时间：2016-12-10 22:59
功能描述：
	使用https协议访问网页
	可设置忽略gzip解码
历史改动：
	2016-xx-xx: xxxxxx
'''
class HttpsAccess:
	def __init__(self):
		pass

	# 初始化https_client
	def init_client(self, host, port, headers = {}, timeout = 5, method = "GET", codec = "utf-8", gzip_ignore = False):
		log = mylog('CommonLib.HttpsAccess.init_client', None)
		self.method = method
		self.headers = headers
		self.codec = codec
		self.gzip_ignore = gzip_ignore
		try:
			self.http_client = HTTPSConnection(host = host, port = port, timeout = timeout)
		except:
			log.exception("init https client failed")
			return False, "init https client failed"
		return True, "suc"

	# set系列函数
	# 必须在init_client()函数后执行，中途改变访问策略
	def set_codec(self, codec):
		self.codec = codec

	def set_gzip_ignore(self, gzip_ignore):
		self.gzip_ignore = gzip_ignore
	
	def set_method(self, method):
		self.method = method
	
	def set_headers(self, headers):
		self.headers = headers

	# 根据相对路径获取访问结果
	def get_response(self, path):
		try:
			self.http_client.request(method = self.method,
									 url = path,
									 headers = self.headers)
			response = self.http_client.getresponse()
			response = response.read()
		except:
			return False, "https access failed: %s" % traceback.format_exc()
		if self.gzip_ignore is False:
			try:
				compressedstream = StringIO.StringIO(response)
				gziper = gzip.GzipFile(fileobj = compressedstream)
				response = gziper.read()
			except:
				# msg引用：DataAPI.DatayesAPI
				return False, "read gzip stream failed :%s" % traceback.format_exc()
		try:
			response = response.decode(self.codec)
		except:
			# msg引用：DataAPI.DatayesAPI
			return False, "decode failed: %s" % traceback.format_exc()
		return True, response


if __name__ == '__main__':
	obj = HttpsAccess()
	flag, msg = obj.init_client(host = '122.224.113.122', port = 443, headers = {},\
								timeout = 5, method = "POST", codec = "utf-8",\
								gzip_ignore = False)
	print flag
	print msg
	flag, msg = obj.get_response("")
	print flag
	print msg
	'''
	flag, msg = obj.init_client(host = 'api.wmcloud.com', 
								port = 443, 
								headers = {"Authorization": "Bearer 62d0d2f732ce5028ce5ffd6f3d86cc8f27ff4faa1405f7626fafda7b798dd1f8",
										   "Accept-Encoding": "gzip, deflate"}, 
								timeout = 5, 
								method = "GET", 
								codec = "utf-8", 
								gzip_ignore = False)
	print flag
	print msg
	rq_path = "/data/v1/api/equity/getEqu.json?field=&ticker=&secID=&equTypeCD=A&listStatusCD="
	rq_path2 = "/data/v1/api/market/getSecTips.json?field=&tipsTypeCD="
	rq_path3 = "/data/v1/api/master/getTradeCal.json?field=&exchangeCD=XSHG&beginDate=&endDate="
	flag, msg = obj.get_response(rq_path)
	print flag
	obj.set_gzip_ignore(True)
	flag, msg = obj.get_response(rq_path2)
	print flag
	print msg
	obj.set_gzip_ignore(False)
	flag, msg = obj.get_response(rq_path3)
	print flag
	'''
